<script setup lang="ts">
import { onMounted, ref } from 'vue';
import * as echarts from 'echarts';
import { useRoute } from 'vue-router';
import { DeviceInfoList, HistoryData4Curve } from '@/service/api/bigScreen';
import { startEndtime } from '@/utils/common';
import DeviceDetail from '@/views/breedingManage/deviceManage/modules/device-detail.vue';
import FishSelect from './fish-select.vue';

const route = useRoute();

const props = defineProps({
  marginTop: {
    type: Number,
    default: 30
  },
  marginBottom: {
    type: Number,
    default: 20
  },
  index: {
    type: Number,
    default: 0
  },
});

/* 传感器相关代码 */

onMounted(() => {
  getSensorList();
});
const echartsRef = ref(null);
const sensorList = ref([]);
const showBtn1 = ref(false);
const showBtn2 = ref(false);
const hostData = defineModel<any>('hostData', {
  default: []
});
const farmData = defineModel<any>('farmData', {
  default: []
});
const DeviceDetailRef = ref();
const chartsData = ref({});
const modalVisible = ref(false);
const echartsModalRef = ref(null);
const FishSelect1 = ref();
const getSensorList = () => {
  const farmId = route.query.farmId ? route.query.farmId : '';
  const obj = {
    deviceType: 1,
    farmId,
    pageSize: 1000
  };
  DeviceInfoList(obj).then(res => {
    sensorList.value = res.data?.data;
    // 获取传感器采集数据
    if (sensorList.value.length > 2) {
      getHistoryData4Curve(sensorList.value[props.index].id, 0);
      setTimeout(() => {
        FishSelect1.value?.setCheckId(sensorList.value[props.index].id, sensorList.value[props.index].deviceName);
      });
    }
  });
};
const getHistoryData4Curve = (deviceId: any, type: any) => {
  const { startTime, endTime } = startEndtime();
  const obj = {
    startTime,
    endTime,
    deviceId
  };
  HistoryData4Curve(obj).then(res => {
    const arr = []; // 采集时间
    const arr1 = []; // 采集数值
    const _data = res.data;
    chartsData.value[type] = {
      arr,
      arr1
    };
    if (_data.length > 0) {
      _data.forEach(item => {
        arr.push(item.time.split(' ')[1]);
        arr1.push(item.average);
      });
      setEchartsInfo(arr, arr1, type);
    }
  });
};
const setShowBtnVisible = async (type: number) => {
  if (type === 1) showBtn1.value = true;
  if (type === 2) showBtn2.value = true;
};
const setEchartsInfo = (arr: any, arr1: any, type: any) => {
  const chart = echarts.init(echartsRef.value);
  if (type === 0) {
    chart.setOption(EchartsOption(arr, arr1));
  }
};
const EchartsOption = (data: any, dataList: any) => {
  return {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data,
      axisLabel: {
        textStyle: {
          color: '#A2DEFF'
        }
      }
    },
    grid: {
      top: 30,
      bottom: 20
    },
    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: '#3758fd' }, // 0% 处的颜色
      // {offset: 0.5, color: '#d9c9b7'}, // 50% 处的颜色
      { offset: 1, color: '#379afd' } // 100% 处的颜色
    ]),
    yAxis: {
      type: 'value',
      axisLabel: {
        textStyle: {
          color: '#A2DEFF'
        }
      },
      splitLine: {
        show: true, // 显示网格线
        lineStyle: {
          color: ['#21466A'], // 网格线颜色
          width: 1, // 网格线宽度
          type: 'solid' // 网格线类型，这里设置为虚线
        }
      }
    },
    series: [
      {
        data: dataList,
        type: 'line',
        areaStyle: {},
        smooth: true
      }
    ]
  };
};
const showChartsModal = (type: number) => {
  modalVisible.value = true;
  setTimeout(() => {
    setModalEchartsInfo(chartsData.value[type].arr, chartsData.value[type].arr1, type);
  }, 100);
};
const setModalEchartsInfo = (arr: any, arr1: any, type: number) => {
  const chart = echarts.init(echartsModalRef.value);
  if (type === 0) {
    chart.setOption(ModalEchartsOption(arr, arr1));
  } else {
    chart.setOption(ModalEchartsOption(arr, arr1));
  }
};
const getDetail = (type: number) => {
  const id = document.getElementById(`FishSelect${type}`)?.dataset.id;
  const data = sensorList.value.find(item => item.id.toString() === id);
  DeviceDetailRef.value?.setRowData(data);
};
const ModalEchartsOption = (data: any, dataList: any) => {
  return {
    tooltip: {
      trigger: 'axis',
      textStyle: {
        fontSize: 16
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data,
      axisLabel: {
        fontSize: 16
      }
    },
    grid: {
      top: 40,
      bottom: 30,
      left: 40,
      right: 30
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 16
      },
      splitLine: {
        show: true, // 显示网格线
        lineStyle: {
          color: ['#21466A'], // 网格线颜色
          width: 1, // 网格线宽度
          type: 'solid' // 网格线类型，这里设置为虚线
        }
      }
    },
    series: [
      {
        data: dataList,
        type: 'line',
        areaStyle: {},
        smooth: true
      }
    ]
  };
};
/* 传感器相关代码 */
</script>

<template>
  <div>
    <div class="Card1">
      <div class="card1-warp" :style="{marginTop: `${props.marginTop}px`, marginBottom: `${props.marginBottom}px`}">
        <div class="card1-header">
          <img src="../../../assets/imgs/breedDetails/title_cgq@2x.png" alt="" />
          <FishSelect
            v-if="sensorList.length > 0"
            id="FishSelect1"
            ref="FishSelect1"
            :list="sensorList"
            @change="id => getHistoryData4Curve(id, 0)"
          />
        </div>
        <div
          ref="echartsRef"
          class="echarts"
          oncontextmenu="return false;"
          @click.right="setShowBtnVisible(1)"
          @click.left="showBtn1 = false"
          @dblclick="showChartsModal(0)"
        />
        <div v-if="showBtn1" class="chart-btn-wrapper1">
          <AButton class="chart-btn" @click="getDetail(1)">查看详情</AButton>
        </div>
      </div>
    </div>
    <div>
      <AModal v-model:open="modalVisible" :footer="null" :width="1366" title="传感器详情" destroy-on-close>
        <div class="pt-20px">
          <div ref="echartsModalRef" style="width: 100%; height: 600px"></div>
        </div>
      </AModal>
    </div>

    <div>
      <DeviceDetail ref="DeviceDetailRef" v-model:hostData="hostData" v-model:farmData="farmData" :disabled="false" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.Card1 {
  width: 510px;
  height: 260px;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;

  .card1-header {
    display: flex;
    align-items: center;

    img {
      width: 90px;
      height: 34px;
    }
  }

  .card1-warp {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 30px;
    position: relative;

    .chart-btn-wrapper1 {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translateX(-50%);
      z-index: 9;
    }
    .chart-btn-wrapper2 {
      position: absolute;
      left: 50%;
      top: 70%;
      transform: translateX(-50%);
      z-index: 9;
    }
    .echarts {
      flex: 1;
    }
  }
}
</style>
